import store from '@/store'
//导入获取菜单数据的方法
import { getMenuList } from '@/api/user';

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise((resolve, reject) => {
      getMenuList().then(res => {
        let accessedRoutes;//存放对应权限的路由信息
        //如果状态码为200，则表示成功
        if (res.code === 200) {
          accessedRoutes = filterAsyncRoutes(res.data, roles)
        } 
        // 将路由信息保存到store中
        commit("SET_ROUTES", accessedRoutes);
        resolve(accessedRoutes);
      }).catch(error => {
        reject(error);
      });
    })
  }
}


/**
 * @param {Array} value
 * @returns {Boolean}
 * @example see @/views/permission/directive.vue
 */
export default function checkPermission(value) {
  if (value && value instanceof Array && value.length > 0) {
    const roles = store.getters && store.getters.roles
    const permissionRoles = value

    const hasPermission = roles.some(role => {
      return permissionRoles.includes(role)
    })
    return hasPermission
  } else {
    console.error(`need roles! Like v-permission="['admin','editor']"`)
    return false
  }
}
